<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2018/7/10
 * Time: 9:27
 */

namespace app\admin\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Login extends Controller
{
    /*
     * 登录界面展示
     * */
    public function index()
    {
        if(Session::get('username'))
        {
            $this->error('您已经登录过了','admin/index/index');
        }
        return $this->fetch();
    }

    //检测输入验证码是否正确
    /*public function check()
    {
        $data = input('post.');
        if(!captcha_check($data['code']))
        {
            $this->error('验证码不正确');
        }else{
            $this->success('ok');
        }
    }*/

    /**
     * 后台登录逻辑
     */
    public function login()
    {
       $username = Request::instance()->param('username');
       $password = Request::instance()->param('password');
       if(empty($username) || empty($password))
       {
           $this->error('登录失败','admin/login/index');
       }
       $admin_user = Db::table('admin_user')->where('username',$username)->limit(1)->select();
    /*var_dump($admin_user);exit;*/
       if(!empty($admin_user))
       {
           if($admin_user[0]['password'] === $password)
           {
               $time = time();       //登录时间
               $username = $admin_user[0]['username'];
               Session::set('username',$username);

               //TODO:获取后台登录的IP  TP5有一个自带的获取Ip的方法  request()->ip()
               Db::table('admin_user')->where('username',$username)->update(['login_time'=>$time]);
               $this->success('登录成功','admin/index/index');
           }
       }
       $this->error('用户名或者密码错误','admin/login/index');

    }

    /**
     * 后台登出逻辑
     */
    public function logout()
    {
        Session::delete('username');
        return redirect('admin/login/index');
    }
    //halt()的用法
    public function hhalt()
    {
        $username = 'admins';
        $user = model('AdminUser')->get(['username'=>$username]);
        dump($user['password']);exit;
        halt($user);
    }
    //获取访问IP
    public function getIp()
    {
        $ip = request()->ip();
        return $ip;
    }
    //session初体验
    public function sess()
    {
        Session::set('hello','worlds');

        //Cache::set('hello','world',10);

    }

    public function cac()
    {
        //清空缓存
        Cache::rm('hello');
    }

    public function getCac()
    {
        //return Cache::get('hello')?Cache::get('hello'):NUll;
        //return Session::get('hello')?Session::get('hello'):'session已经失效';
       // return Cache::get('username')?Cache::get('username'):'缓存已经失效';
        return Session::get('username')?Session::get('username'):'缓存已经失效';
    }
}